class Bid < ActiveRecord::Base
  belongs_to :auction
  belongs_to :user

  def self.make_bid(user, bid, auction_id)
    auction = Auction.find(auction_id)

    if (auction == nil ||
        Time.now > auction.enddate)
      return
    end


    if auction.bid < bid.to_i
      current_max_bid = auction.winner
      if current_max_bid &&
          current_max_bid.user_id == user
        current_max_bid.max = bid
        if auction.reservation >= bid.to_i &&
          auction.bid = bid
          auction.save
        end
        current_max_bid.save
      else
        newbid = Bid.new
        newbid.user_id = user
        newbid.auction_id = auction_id
        newbid.max = bid
        newbid.datetime = Time.now
        newbid.save

        if auction.reservation >= bid.to_i
          new_max_bid = bid.to_i
        elsif not current_max_bid
          new_max_bid = auction.bid + 1
        elsif (current_max_bid.max >= bid.to_i)
          new_max_bid = bid
        else
          new_max_bid = current_max_bid.max + 1
        end
      
        auction.bid = new_max_bid
        auction.save
      end

      remove_fixed_price(auction_id)

      if auction.dynamic_auction
        auction.ad.enddate = Time.now + 3600 * auction.dynamic_auction.timeout
        auction.ad.save
      end

      Email.notifyAuctionBid(auction)
    end
  end

  def self.remove_fixed_price(auction_id)
    begin
      auction = Auction.find(auction_id)
      fixed_auction = auction.fixed_auction
      fixed = fixed_auction.fixed

      Fixed.delete(fixed)
      FixedAuction.delete(fixed_auction)
    rescue
      #There were probably no fixed price to remove
    end
  end

  def self.history(auction_id)
    bid_history = Array.new
    auction = Auction.find(auction_id)
    current_max = Bid.new(:max => 0)
    auction.bids.each do |b|

      if auction.reservation > b.max
        bid = b.max
        current_max = b
      elsif b.max > current_max.max
        bid = current_max.max + 1
        current_max = b
      elsif b.max <= current_max.max
        bid = b.max

        bid_history.push(b)
      else
        next
      end

      bid_history.push(Bid.new(:datetime => current_max.datetime, :user => current_max.user, :max => bid))
    end
    bid_history
  end
end
